package com.rongchuang.autoopendevice.service.impl;

import com.alibaba.fastjson2.JSON;
import com.rongchuang.autoopendevice.bean.PulseAction;
import com.rongchuang.autoopendevice.service.ControlRelayService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.web.reactive.function.client.WebClient;

@Service
public class ControlRelayServiceImpl implements ControlRelayService {
    private static final Logger LOGGER = LoggerFactory.getLogger(ControlRelayServiceImpl.class);
    @Value("${weipeng.pulseurl}")
    private String pulseurl;
    @Value("${weipeng.token}")
    private String token;
    @Value("${weipeng.pulsecount}")
    private int pulsecount;
    @Value("${weipeng.pulsepara}")
    private String pulsepara;
    /**
     * 立即打开继电器，duration秒后关闭
     */
    @Override
    public void openPulse(String deviceId) {
        PulseAction pulseAction = buildPulse();
        pulseAction.setDevid(deviceId);
        LOGGER.info("----------开始发送脉冲----------");
        String s = sendPostRequest(pulseAction);
        LOGGER.info("响应体数据：{}", s);
        LOGGER.info("----------发送脉冲完毕----------");

    }
    private PulseAction buildPulse(){
        PulseAction pulseAction = new PulseAction();
        pulseAction.setToken(token);
        pulseAction.setCount(pulsecount);
        pulseAction.setPara(pulsepara);
        return pulseAction;
    }
    private String sendPostRequest(PulseAction pulseAction) {
        // 创建WebClient对象
        WebClient webClient = WebClient.create();



        // 请求头设置
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);

        // 请求体数据
        String jsonString = JSON.toJSONString(pulseAction);
        LOGGER.info("请求体数据：{}", jsonString);

        // 发送POST请求并获取响应
        return webClient.post()
                .uri(pulseurl)
                .headers(httpHeaders -> httpHeaders.putAll(headers))
                .bodyValue(jsonString)
                .retrieve()
                .bodyToMono(String.class)
                .block();
    }
}
